import paddle
import pandas as pd
import numpy as np
import sys
import paddle.fluid as fluid

use_cuda = False
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
paddle.enable_static()
infer_exe = fluid.Executor(place)
inference_scope = fluid.core.Scope()


def test_predict(input_file, model_file):
    """

    :param input_file: 被分析数据的文件路径
    :param model_file: 调用算法model的路径
    :return: 输出预测的json结果，格式如：{'predict': 1}
    """
    array = []
    with open(input_file) as file_obj:
        array = eval(file_obj.read())
        if len(array) != 28*28:
            raise Exception("输入文件为长度为784的一维数组")
    im = np.array(array).reshape(1, 1, 28, 28).astype(np.float32)  # 返回新形状的数组,把它变成一个 numpy 数组以匹配数据馈送格式。
    im = im / 255.0 * 2.0 - 1.0  # 归一化到【-1~1】之间
    with fluid.scope_guard(inference_scope):
        # 获取训练好的模型
        [inference_program,
         feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(model_file, infer_exe)
        img = im

        results = infer_exe.run(program=inference_program,
                                feed={feed_target_names[0]: img},
                                fetch_list=fetch_targets)
        lab = np.argsort(results)
        # print(lab)
        return {"predict": lab[0][0][-1]}


if __name__ == '__main__':
    # print(test_predict("../test_data/test_4.txt", "../model/test_model"))  # 测试参数
    test_predict(sys.argv[1], sys.argv[2])
